// HTML模板
const makeHtmlAttributes = (attributes) => {
  if (!attributes) {
    return '';
  }

  const keys = Object.keys(attributes);
  return keys.reduce((result, key) => (result += ` ${key}="${attributes[key]}"`), '');
};

async function htmlTemplate({ attributes, files, meta, publicPath, title }) {
  // 注入JS
  const scripts = (files.js || [])
    .map(({ fileName }) => {
      return `<script src="${publicPath}${fileName}"></script>`;
    })
    .join('\n');

  // 注入CSS
  const links = (files.css || [])
    .map(({ fileName }) => {
      const attrs = makeHtmlAttributes(attributes.link);
      return `<link href="${publicPath}${fileName}" rel="stylesheet"${attrs}>`;
    })
    .join('\n');

  // 循环生成META标签
  const metas = meta
    .map((input) => {
      const attrs = makeHtmlAttributes(input);
      return `<meta${attrs}>`;
    })
    .join('\n');

  // 循环生成其它标签
  const extras = (attributes.script || [])
    .map((input) => {
      const attrs = makeHtmlAttributes(input.attr);
      return `<${input.type}${attrs}></${input.type}>`;
    })
    .join('\n');

  return `
  <!doctype html>
  <html${makeHtmlAttributes(attributes.html)}>
    <head>
      ${metas}
      <title>${title}</title>
      ${links}
    </head>
    <body>
      ${extras}
      ${scripts}
    </body>
  </html>`;
}

export default htmlTemplate
